# Copyright 2012 Brett Ponsler
# This file is part of siriviewer.
#
# siriviewer is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# siriviewer is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with siriviewer.  If not, see <http://www.gnu.org/licenses/>.
''' '''
from PyQt4 import QtGui, QtCore
from PyQt4.Qt import SIGNAL

from siriviewer.objects import BaseObject
from pysiriproxy.constants import Directions


class Button(BaseObject):
    ''' '''
    # @todo: set this in a config file
    margins = 25

    def configure(self):
        ''' '''
        self.setMargins(left=self.margins, right=self.margins)

    def createElements(self):
        ''' '''
        # @todo: it would be nice to have a subclass of QPushButton that could
        #        properly handle adding newlines to any text that didn't fit
        buttonText = self.getProperty("text")
        self.__button = QtGui.QPushButton(buttonText)
        self.__button.adjustSize()
        self.__button.setStyleSheet("background-color: white")

        # Add a margin to both sides of the button
        self.__button.setMaximumWidth(self.width - (self.margins * 2))

        return [self.__button]

    def setupConnections(self):
        ''' '''
        self.__buttonCommand = self.__getButtonCommand()
        self.connect(self.__button, SIGNAL("clicked()"), self.__buttonClicked)

    def __buttonClicked(self):
        '''Called in the event that the button was clicked.'''
        # Issue the button command to siriviewer
        self.controller.testFilters(self.__buttonCommand,
                                    Directions.From_iPhone)

    def __getButtonCommand(self):
        ''' '''
        commands = self.getItems(["properties", "commands"])
        sendCommands = self.findClassInList(commands, "SendCommands")
        subCommands = self.getItems(["properties", "commands"],
                                   data=sendCommands)

        startRequest = self.findClassInList(subCommands, "StartRequest")        
        return startRequest

    def findClassInList(self, objectList, className):
        ''' '''
        returnObj = None

        for obj in objectList:
            if obj.get('class') == className:
                returnObj = obj
                break

        return returnObj
